package com.mengwen.backstage.controller.partner;

import com.mengwen.backstage.pojo.Partner;
import com.mengwen.backstage.service.PartnerService;
import com.mengwen.backstage.util.JwtUtil;
import com.mengwen.backstage.util.MD5Util;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author LiangYonghui
 * @date 2020/4/7 10:42
 * @description 合伙人登录
 */
@Controller
public class PartnerLoginController {

    private static final Log LOG = LogFactory.getLog(PartnerLoginController.class);


    @Autowired
    PartnerService partnerService;

    /**
     * 合伙人进入登录页面
     * @return
     */
    @RequestMapping("/partner/login")
    public String partnerToLogin(){
        return "partner_login";
    }


    /**
     * 合伙人登录
     * @param response
     * @param httpServletRequest
     * @param model
     * @return
     * @throws IOException
     * @throws ServletException
     */
    @RequestMapping("/mengwen/partner/login")
    public String partnerLogin(HttpServletResponse response, HttpServletRequest httpServletRequest, Model model) throws IOException, ServletException {
        String accountNumber = httpServletRequest.getParameter("account_number");
        String password = httpServletRequest.getParameter("password");
        String md5Password = MD5Util.md5Encrypt32Upper(password);
        Partner partner = partnerService.login(accountNumber, md5Password);
        if (partner != null) {
            LOG.info("合伙人" + partner.getNickname() +"首次登录成功：" + partner.getOpenid());
            Integer state = partnerService.findStateByAccountNumber(accountNumber);
            if (state == 0) {
                partnerService.updateStateByAccountNumber(accountNumber);
            }
            model.addAttribute("partner",partner);
            // 分发jwttoken
            String partnerToken = JwtUtil.genePartnerJsonWebToken(partner);
            System.out.println(partnerToken);
            model.addAttribute("partnerToken",partnerToken);
            System.out.println("首次登录");
            model.addAttribute("partner",partner);
            return "partner_page";
        }else {
            // 账号密码不正确：
            model.addAttribute("errorMsg","账号或密码错误");
            return "partner_login";

        }


    }



}
